<template>
  <!-- 条件搜索 -->
  <el-form ref="form" :model="searchForm" label-width="80px">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="镜像名称">
          <el-input v-model="searchForm.rangeName" placeholder="请输入镜像名称" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="镜像描述">
          <el-input v-model="searchForm.rangeDesc" placeholder="请输入镜像描述" />
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="fetchRangeList">查询</el-button>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="dialogUploadVisible = true">上传镜像文件</el-button>
      </el-col>
    </el-row>
  </el-form>

  <!-- 列表展示 -->
  <el-table :data="tableData" stripe border style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="rangeName" label="靶场名称" width="180" />
    <el-table-column prop="rangeType" label="类型" width="120" />
    <el-table-column prop="difficultyId" label="难度等级" width="120" />
    <el-table-column prop="rangeDesc" label="描述" />
    <el-table-column prop="uploader" label="上传者" width="120" />
    <el-table-column prop="uploadTime" label="创建时间" width="180" align="center" />
    <el-table-column prop="updater" label="修改者" width="120" />
    <el-table-column prop="updateTime" label="修改时间" width="180" align="center" />
    <el-table-column fixed="right" label="操作" min-width="180px">
      <template #default="scope">
        <el-button size="small" type="warning" @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="deleteRange(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页组件 -->
  <Pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :total="total"
      @change="handlePageChange"
  />
  <!-- 上传弹窗 -->
  <el-dialog v-model="dialogUploadVisible" title="上传镜像文件" width="50%">
    <el-form :model="uploadForm" label-width="120px">
      <el-form-item label="镜像名称">
        <el-input v-model="uploadForm.targetRangeName" />
      </el-form-item>

      <el-form-item label="镜像类型">
        <el-input v-model="uploadForm.targetRangeType" />
      </el-form-item>

      <el-form-item label="难度等级">
        <el-input-number v-model="uploadForm.difficultyId" :min="1" :max="5" />
      </el-form-item>

      <el-form-item label="描述信息">
        <el-input v-model="uploadForm.description" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item label="flag存储位置">
<!--        下拉选择-->
        <el-select v-model="uploadForm.flagPath" placeholder="请选择">
          <el-option label="/root" value="/root">/root</el-option>
          <el-option label="/tmp" value="/tmp">/tmp</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="暴露端口">
        <el-input v-model="uploadForm.exposePort" />
      </el-form-item>
      <el-form-item label="选择文件">
        <el-upload
            ref="uploadRef"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            list-type="text"
        >
          <el-button slot="trigger">选择文件</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitUpload" :disabled="uploading">
          {{ uploading ? '上传中...' : '提交上传' }}
        </el-button>
        <el-button @click="dialogUploadVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 编辑弹窗 -->
  <el-dialog v-model="dialogEditVisible" title="编辑镜像信息" width="50%">
    <el-form :model="editForm" label-width="120px">
<!--      <el-form-item label="镜像名称">
        <el-input v-model="editForm.rangeName" />
      </el-form-item>-->

      <el-form-item label="镜像类型">
        <el-input v-model="editForm.rangeType" />
      </el-form-item>

      <el-form-item label="难度等级">
        <el-input-number v-model="editForm.difficultyId" :min="1" :max="5" />
      </el-form-item>

      <el-form-item label="描述信息">
        <el-input v-model="editForm.rangeDesc" type="textarea" :rows="3" />
      </el-form-item>

      <el-form-item label="容器暴露的端口">
        <el-input v-model="editForm.exposePort" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitEdit">保存更改</el-button>
        <el-button @click="dialogEditVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">

import { ref, reactive } from 'vue';
// 分页数据
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
const dialogUploadVisible = ref(false);
const dialogEditVisible = ref(false);
const uploadRef = ref(null);
const uploading = ref(false);

// 上传表单
const uploadForm = ref({
  targetRangeFile: null as Blob | null,
  targetRangeName: '',
  targetRangeType: '',
  difficultyId: 1,
  description: '',
  exposePort: '',
  flagPath: ''
});

// 编辑表单
const editForm = ref({
  rangeId: '',
  rangeName: '',
  rangeType: '',
  difficultyId: 1,
  rangeDesc: '',
  exposePort: ''
});

// 搜索表单
const searchForm = reactive({
  rangeName: '',
  rangeDesc: ''
});

// 文件变化处理
const handleFileChange = (file) => {
  uploadForm.value.targetRangeFile = file.raw;
};

// 获取列表
const fetchRangeList = async () => {
  try {
    const res = await rangeMange.list({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchForm
    });
    console.log('res:', res);
    if (res.code === 200) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  } catch (error) {
    console.error('获取镜像列表失败:', error);
    alert('获取镜像列表失败');
  }
};
//  分页处理
const handlePageChange = (newPageNum: number, newPageSize: number) => {
  pageNum.value = newPageNum;
  pageSize.value = newPageSize;
  fetchRangeList();
};
// 修改后的submitUpload方法
const submitUpload = async () => {
  if (!uploadForm.value.targetRangeFile) {
    ElMessage.error('请选择要上传的文件');
    return;
  }

  const formData = new FormData();
  formData.append('targetRangeFile', uploadForm.value.targetRangeFile); // 直接使用raw文件对象

  // 添加其他字段（确保字段名与后端@RequestParam一致）
  formData.append('targetRangeName', uploadForm.value.targetRangeName);
  formData.append('targetRangeType', uploadForm.value.targetRangeType);
  formData.append('difficultyId', uploadForm.value.difficultyId.toString());
  formData.append('description', uploadForm.value.description);
  formData.append('flagPath', uploadForm.value.flagPath);
  if (uploadForm.value.exposePort) {
    formData.append('exposePort', uploadForm.value.exposePort);
  }

  try {
    uploading.value = true;
    await rangeMange.upload(formData);
    ElMessage.success('上传成功');
    dialogUploadVisible.value = false;
    fetchRangeList();
  } catch (error) {
    console.error('上传失败:', error);
  } finally {
    uploading.value = false;
  }
};

// 打开编辑对话框
const openEditDialog = (row: any) => {
  editForm.value = {
    rangeId: row.rangeId,
    rangeName: row.rangeName,
    rangeType: row.rangeType,
    difficultyId: row.difficultyId,
    rangeDesc: row.rangeDesc,
    exposePort: row.exposePort || ''
  };
  dialogEditVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  try {
    await rangeMange.update({
      rangeName: editForm.value.rangeName,
      rangeType: editForm.value.rangeType,
      difficultyId: editForm.value.difficultyId,
      rangeDesc: editForm.value.rangeDesc,
      exposePort: editForm.value.exposePort
    });
    dialogEditVisible.value = false;
    fetchRangeList();
  } catch (error) {
    console.error('更新失败:', error);
    alert('更新失败');
  }
};

// 删除镜像
const deleteRange = async (row: any) => {
  console.log('row:', row.rangeId);
  if (confirm(`确定要删除【${row.rangeId}】吗？`)) {
    try {
      await rangeMange.delete(row.rangeId); // 直接传入字符串 ID
      fetchRangeList();
    } catch (error) {
      console.error('删除失败:', error);
      alert('删除失败');
    }
  }
};

// 重置上传表单
const resetUploadForm = () => {
  uploadForm.value = {
    targetRangeFile: null,
    targetRangeName: '',
    targetRangeType: '',
    difficultyId: 1,
    description: '',
    exposePort: '',
    flagPath:  ''
  };
  if (uploadRef.value) {
    uploadRef.value.clearFiles(); // 清除文件选择
  }
};

// 页面加载初始化数据
import { onMounted } from 'vue';

import Pagination from "@/components/common/pagination/Pagination.vue";
import {ElMessage} from "element-plus";
import rangeMange from "@/api/Backend/rangeMange.ts";

onMounted(() => {
  fetchRangeList();
});
</script>

<style scoped>
.el-form-item__content {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-table {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
}
</style>
